import os
import tempfile
import subprocess
import sys

LABEL_NONE=0
LABEL_ORANGE=1
LABEL_RED=2
LABEL_YELLOW=3
LABEL_BLUE=4
LABEL_PURPLE=5
LABEL_GREEN=6
LABEL_GREY=7



class MacFinderColourFile:

    def __init__(self, files, labelNum):
        # Write the list of files to label to a temp file
        (tmpFH, tmpPath) = tempfile.mkstemp('.txt')
        os.write(tmpFH, "\n".join(files))
        os.close(tmpFH)
        
        # Open a pipe to and from the applescript interpreter
        asInterpreter = subprocess.Popen(
            "/usr/bin/osascript",
            shell=True,
            stdin=subprocess.PIPE,
            stdout=sys.stdout)
        
        # The script we'll send it
        script = [
            'tell application "Finder"',
            'set fileList to (POSIX file "%s")' % (tmpPath),
            'set labelColor to %i' % (labelNum),
            'try',
            'set fh to open for access fileList',
            'repeat with thisFile in (read fh using delimiter (ASCII character 10))',
            'set label index of item (thisFile as POSIX file) to labelColor',
            'end repeat',
            'close access fh',
            'on error',
            'try',
            'close access fh',
            'end try',
            'end try',
            'end tell'
        ]
        
        asInterpreter.stdin.write("\n".join(script))
        asInterpreter.stdin.close()
        asInterpreter.wait()
        os.unlink(tmpPath)
    
